package org.sjsu.freedoor.model;

import java.util.ArrayList;
import java.util.Collection;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.sjsu.freedoor.util.Utilities;

public class OfferList {
	public final static String OFFERS_ARRAY_KEY = "offers";
	
	private Collection<Offer> m_list;
	
	public OfferList() {
		m_list = new ArrayList<Offer>();
	}
	
	public boolean loadOffers(JSONArray jsonArr) {
		m_list.clear();
		
		try {
			for (int i = 0; i < jsonArr.length(); i++) {
				Offer o = new Offer();
				if(o.loadOffer(jsonArr.getJSONObject(i)))
					m_list.add(o);
			}
		} catch (JSONException e) {
			System.out.println("Invalid OfferList jsonArray: " + jsonArr.toString());
			return false;
		}
		
		return true;
	}
	
	public boolean loadOffers(JSONObject jsonObj) {
		try {
			JSONArray offerArr = jsonObj.optJSONArray(OFFERS_ARRAY_KEY);
			if(offerArr != null){
				return loadOffers(jsonObj.getJSONArray(OFFERS_ARRAY_KEY));
			}
			else
			{
				Offer o = new Offer();
				if(o.loadOffer(jsonObj)){
					m_list.add(o);
					return true;
				}
				else{
					return false;
				}
				
			}
		} catch (JSONException e) {
			System.out.println("Invalid OfferList jsonArray: " + jsonObj.toString());
			return false;
		}
	}
	
	public boolean loadOffers(String jsonString) {
		try {
			JSONObject jsonObj = new JSONObject(jsonString);
			return loadOffers(jsonObj);
		} catch (JSONException e) {
			// might be json array
			try {
				JSONArray jsonArr = new JSONArray(jsonString);
				return loadOffers(jsonArr);
			} catch (JSONException e2) {
				System.out.println("Invalid OfferList jsonString: " + jsonString.toString());
				return false;
			}
		}
	}
	
	public String toJsonString(boolean encapsulateWithCurlyBraces, boolean useListKey)
	{
		StringBuilder str = new StringBuilder();
		if(encapsulateWithCurlyBraces)
			str.append("{");
		if(useListKey || encapsulateWithCurlyBraces)
			str.append("\"" + OFFERS_ARRAY_KEY + "\":");
		str.append("[");
		
		for(Offer o : m_list)
			str.append(o.toJsonString() + ",");
		if(m_list.size() > 0)
			str.deleteCharAt(str.length()-1);
		
		str.append("]");
		if(encapsulateWithCurlyBraces)
			str.append("}");
		
		return str.toString().replaceAll("\\\"", "\""); //get rid of escaped character sequences
	}
	
	public JSONObject toJsonObject()
	{
		return Utilities.toJsonObject(this.toJsonString(true, true));
	}
	
	public JSONArray toJsonArray()
	{
		return Utilities.toJsonArray(this.toJsonString(false, false));
	}
	
	public Collection<Offer> getList() {
		return m_list;
	}
	
	public boolean add(Offer ofr) {
		//Check for duplicate offer
//		for(Offer o : m_list) {
//			if(o.getEmail().equals(ofr.getEmail()) && o.getMessage().equals(ofr.getMessage()) && o.getId().equals(ofr.getId()))
//				return false;
//		}
		m_list.add(ofr);
		return true;
	}
}
